class Ball {
  constructor(x, y, radius, color) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.color = color;
    this.vx = (Math.random() - 0.5) * 5; // X轴速度
    this.vy = (Math.random() - 0.5) * 5; // Y轴速度
  }

  draw(ctx) {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.closePath();
  }

  update(canvasWidth, canvasHeight) {
    if (this.x + this.radius > canvasWidth || this.x - this.radius < 0) {
      this.vx = -this.vx;
    }
    if (this.y + this.radius > canvasHeight || this.y - this.radius < 0) {
      this.vy = -this.vy;
    }
    this.x += this.vx;
    this.y += this.vy;
  }
}

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

//  开启硬件加速
// canvas {
//   transform: translateZ(0);
// }
canvas.style.cssText = "transform: translateZ(0);";

const balls = []; // 存储小球的数组

function animate() {
  requestAnimationFrame(animate);
  ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布

  balls.forEach((ball) => {
    ball.update(canvas.width, canvas.height); // 更新小球位置
    ball.draw(ctx); // 重新绘制小球
  });
}

// 初始化小球并开始动画
for (let i = 0; i < 10; i++) {
  let ball = new Ball(
    Math.random() * canvas.width,
    Math.random() * canvas.height,
    Math.random() * 20 + 10,
    `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`,
  );
  balls.push(ball);
}

animate(); // 开始动画循环

// 距离计算
function checkCollision(ball1, ball2) {
  const dx = ball1.x - ball2.x;
  const dy = ball1.y - ball2.y;
  const distance = Math.sqrt(dx * dx + dy * dy);
  return distance < ball1.radius + ball2.radius;
}

// 碰撞响应
function resolveCollision(ball1, ball2) {
  const dx = ball1.x - ball2.x;
  const dy = ball1.y - ball2.y;
  const distance = Math.sqrt(dx * dx + dy * dy);
  const angle = Math.atan2(dy, dx);
  const sin = Math.sin(angle);
  const cos = Math.cos(angle);

  // 临时存储小球速度
  const speed1 = Math.sqrt(ball1.vx * ball1.vx + ball1.vy * ball1.vy);
  const speed2 = Math.sqrt(ball2.vx * ball2.vx + ball2.vy * ball2.vy);
  const direction1 = (ball1.vx * cos + ball1.vy * sin) / speed1;
  const direction2 = (ball2.vx * cos + ball2.vy * sin) / speed2;

  // 交换速度
  ball1.vx = direction2 * speed1 * cos + direction1 * speed1 * sin;
  ball1.vy = direction2 * speed1 * sin - direction1 * speed1 * cos;
  ball2.vx = direction1 * speed2 * cos + direction2 * speed2 * sin;
  ball2.vy = direction1 * speed2 * sin - direction2 * speed2 * cos;
}
